package com.gton.person.commons.captcha;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @program: PersonalDesign
 * @description: 验证码仓库实现SessionCaptchaRepository
 * @author: GuoTong
 * @create: 2020-11-30 15:16
 **/
@Component
public class RedisCaptchaRepository implements CaptchaRepository<HttpServletRequest> {

    /*注入依赖：这里的这个是redis的模板依赖，方便我们java对于redis操作*/
    @Autowired
    private RedisTemplate redisTemplate;


    private static final String CAPTCHA_SESSION_KEY = "captcha";
    /**
     * the key of captcha in session attributes
     */

    private String captchaSessionKey = CAPTCHA_SESSION_KEY;

    @Override
    public String load(HttpServletRequest request) {
        /*session中加载验证码*/
        //return (String) request.getSession().getAttribute(captchaSessionKey);
        /*redis中加载验证码*/
        /*预防缓存击穿||穿透:从redis中获取验证码*/
        String dataCaptcha = (String) redisTemplate.opsForValue().get(captchaSessionKey);
        //如果没有获取到：情况一：验证码没有存入redis，情况二：验证码过时
        //获取到了验证码就返回出去
        if (dataCaptcha != null) {
            return dataCaptcha;
        } else {
            //没有获取到就往下走：
            // 如何解决，在验证码生产的时候保存验证，如果过时了就自动重新把验证码再次存入redis
            //想到了session:session默认三十分钟。
            String yzm = (String) request.getSession().getAttribute(captchaSessionKey);
            return yzm;

        }
    }

    @Override
    public void save(HttpServletRequest request, String captcha) {
        /*session中保存验证码*/
        //request.getSession().setAttribute(captchaSessionKey, captcha);
        /*redis中保存验证码*/
        redisTemplate.opsForValue().set(captchaSessionKey, captcha);
        //设置过期时间； TimeUnit.MILLISECONDS  毫秒:设置默认时间是SECONDS秒：60秒
        redisTemplate.expire(captchaSessionKey, 60, TimeUnit.SECONDS);

        //备份到session一份
        request.getSession().setAttribute(captchaSessionKey, captcha);
    }

    /**
     * @return sessionKey
     */

    public String getCaptchaSessionKey() {
        return captchaSessionKey;
    }

    /**
     * @param captchaSessionKey sessionKey
     */
    public void setCaptchaSessionKey(String captchaSessionKey) {
        this.captchaSessionKey = captchaSessionKey;
    }
}